/*********************************************************************\
*
*                  (c) lkc
*                  All Rights Reserved. lkc Confidential
*
\*********************************************************************/
/*********************************************************************\
*   Title                      :
*
*   Module Description         :
*
*   Author                     : lkc
*
*   Created                    : 2019-3-7
*
\*********************************************************************/
#include <stdio.h>
#include <thread>
#include "UtilityTH.h"
#include "MotorDrv8885.h"
#include "GpioLeds.h"
#include "PwmUserspace.h"


static const int STEP_DEFAULT = 20;//电机默认20步旋转一圈
static const int REDUCE_RATIO = 64;//减速箱减速比
static const int MICRO_STEP = 16;//电机驱动芯片细分比例
static bool motorIsRuning = false;
static bool motorDirIsAdd = true;

static const bool FOCUS_ADD_IS_TRUE = true;
static GpioLeds motorDir("motor_dir");
static GpioLeds motorNsleep("motor_nsleep");
static GpioLeds motorTrq("motor_trq");
static Pwm stepPwm(0,0);

void MotorInit()
{
    MotorEnable(false);
    motorTrq.SetActive(false);
}

void MotorDirFocusAdd()
{
    motorDir.SetActive(FOCUS_ADD_IS_TRUE);
    motorDirIsAdd = true;
}

void MotorDirFocusDec()
{
    motorDir.SetActive(!FOCUS_ADD_IS_TRUE);
    motorDirIsAdd = false;
}

bool GetMotorDirIsAdd()
{
    motorDir.SetActive(motorDirIsAdd);
    return motorDirIsAdd;
}

void MotorEnable(bool isTrue)
{
    motorNsleep.SetActive(isTrue);
    motorIsRuning = isTrue;
}

bool GetMotorRunState()
{
    motorNsleep.SetActive(motorIsRuning);
    return motorIsRuning;
}

void MotorSetSpeed(float rpm)
{
//    printf("rpm is %.1f\n",rpm);
    long cycleTime = static_cast<long long>(60)*1000000000/(rpm*STEP_DEFAULT*REDUCE_RATIO*MICRO_STEP);
    stepPwm.SetCycleTime(cycleTime);
//    printf("the PWM cycle time is %ldns\n",cycleTime);
    stepPwm.SetOnTime(cycleTime*0.5);
}

void MotorTest()
{
    int speed = 30;
    int time = 5000;
    int interval = 20;
//    MotorSetSpeed(200000);
    MotorEnable(true);
//    MotorDirFocusDec();
    MotorDirFocusAdd();
    while((speed<50)&&(time>0))
    {
        MotorSetSpeed(speed++);
        std::this_thread::sleep_for(std::chrono::milliseconds(interval));
        time-=interval;
    }
    std::this_thread::sleep_for(std::chrono::milliseconds(time));
    MotorEnable(false);
}


/********************************************************************\
 *
 * REVISION RECORDS
 *
\*********************************************************************/
/*********************************************************************/
/*
 *
 *
 *
\*********************************************************************/
/*------------------------------The End------------------------------*/
